import { MapView, Marker, Circle, type LatLng } from 'react-native-amap3d';
import { getFindFigInfo, addFight, findCommand } from 'api/police/index';
import React, { useEffect, useState, useReducer, useRef } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import BaseSidebar from 'components/BaseSidebar';
import useDimensions from 'hooks/useDimensions';
import { DraxProvider, DraxView, type Position } from 'react-native-drax';
import { MapCenter } from 'enums/Map'
import BaseDialog from 'components/BaseDialog';
import { SvgXml } from 'react-native-svg';
import { Button, Portal } from 'react-native-paper'
import Xfy from 'assets/police/xfy.svg'
import Zhy from 'assets/police/zhy.svg'
import Car from 'assets/police/car.svg'

// @ts-ignore
import ModalDropdown from 'react-native-modal-dropdown';
interface reducerParams {
  state: {
    disasterPointList: Api.resBody['FightDisasterPointDTO'][];
    commandPostList: Api.resBody['FightCommandPostDTO'][];
  };
  action: {
    type: 'setDisasterPointList' | 'setCommandPostList';
    value: Api.resBody['FightDisasterPointDTO'][] &
    Api.resBody['FightCommandPostDTO'][];
  };
}
function reducer(
  state: reducerParams['state'],
  action: reducerParams['action'],
) {
  switch (action.type) {
    case 'setDisasterPointList': {
      return {
        ...state,
        disasterPointList: action.value,
      };
    }
    case 'setCommandPostList': {
      return {
        ...state,
        commandPostList: action.value,
      };
    }
  }
}
function getPositionFromPoint(value: string): LatLng {
  const reg = /[0-9]+/g;
  const matchList = value.match(reg);
  if (matchList?.length !== 4) {
    throw new Error('没有匹配合适的经纬度');
  } else {
    return {
      latitude: +matchList.slice(2).join('.'),
      longitude: +matchList.slice(0, 2).join('.'),
    };
  }
}
// 渲染圆心作用域组件
function DisasterItems({
  renderList,
  center,
}: {
  renderList: Api.resBody['FightDisasterPointDTO']['disasters'];
  center: LatLng;
}) {
  return (
    <>
      {(renderList ?? []).map((item, index: number) => {
        return (
          <Circle
            center={center}
            fillColor="transparent"
            strokeColor="red"
            radius={item.scope ?? 0}
            key={index}></Circle>
        );
      })}
    </>
  );
}
function withDraxView(WrapComponent: React.JSX) {
  return <WrapComponent></WrapComponent>
}
export default ({
  navigation,
  route: {
    params: { patrolCommandId, patrolPoliceId, position },
  },
}: RootStackScreenProps<'PoliceMap'>) => {
  const hp = useDimensions();
  const [PoliceMapState, dispatch] = useReducer(reducer, {
    disasterPointList: [],
    commandPostList: [],
  });
  const patrolCommandIdRef = useRef(patrolCommandId)
  const MapViewRef = useRef<MapView>(null)
  const [visible, setVisible] = useState(false)
  const [options, setOptions] = useState<any[]>([])
  const [title, setTitle] = useState('指挥长')
  const selectValue = useRef('')
  const currentPosition = useRef<Position>()
  useEffect(() => {
    if (patrolPoliceId) {
      addFight({
        patrolPoliceId,
      }).then(patrolCommandId => {
        patrolCommandIdRef.current = patrolCommandId
        getFindFigInfo({
          patrolCommandId,
        }).then(data => {
          const { disasterPointDTOS, commandPostDTOS } = data;
          dispatch({
            type: 'setCommandPostList',
            value: commandPostDTOS ?? [],
          });
          dispatch({
            type: 'setDisasterPointList',
            value: disasterPointDTOS ?? [],
          });
        });
      });
    } else {
      getFindFigInfo({
        patrolCommandId: patrolCommandId as string,
      }).then(data => {
        MapViewRef.current?.moveCamera({
          target: {
            latitude: +(data.map?.lat as string),
            longitude: +(data.map?.lng as string)
          }
        }, 500)
        const { disasterPointDTOS, commandPostDTOS } = data;
        dispatch({
          type: 'setCommandPostList',
          value: commandPostDTOS ?? [],
        });
        dispatch({
          type: 'setDisasterPointList',
          value: disasterPointDTOS ?? [],
        });
      });
    }
    findCommand({ type: 0 }).then((data) => {
      setOptions(data ?? [])
    })
  }, []);
  const styles = StyleSheet.create({
    icon: {
      width: 60 * hp,
      height: 60 * hp,
      // marginRight: 20
    },
    title: {
      fontSize: 20,
      fontWeight: 'bold',
      color: '#000',
      marginVertical: 20
    }
  });
  return (
    <>
      <Portal>
        <BaseDialog onSubmit={() => {
          MapViewRef.current?.getLatLng(currentPosition.current as Position).then((LatLng) => {
            dispatch({
              type: 'setCommandPostList',
              value: [...PoliceMapState.commandPostList, {
                name: selectValue.current.realName,
                patrolCommandId: patrolCommandIdRef.current,
                coordinate: Object.values(LatLng).join(','),
                type: title === '指挥长' ? '0' : "1"
              }],
            });
            setVisible(false)
          })
        }} visible={visible} setVisible={setVisible} title={title}><ModalDropdown onSelect={(_, value) => {
          selectValue.current = value
        }} renderButtonText={(option) => {
          return <Text>{option.realName}</Text>
        }} style={{
          width: 100
        }} adjustFrame={(styles) => {
          return { width: 100, ...styles, top: styles.top - 20, alignItems: "center" }

        }}
          renderRow={(option, index, isSelected) => {
            return <Text style={{
              fontSize: 12,
              padding: 4
            }} numberOfLines={1}>{option.realName}</Text>
          }}
          dropdownStyle={{
          }} options={options}>
          </ModalDropdown></BaseDialog>
      </Portal>

      <DraxProvider style={{
        flex: 1,
        position: 'relative',
        flexDirection: 'row',
      }}>
        <MapView
          mapType={3}
          myLocationButtonEnabled
          myLocationEnabled
          buildingsEnabled
          ref={MapViewRef}
          compassEnabled={false}
          initialCameraPosition={{
            target: position || MapCenter,
            zoom: 15,
          }}>
          {/* 指挥员marker */}
          {PoliceMapState.commandPostList.map((item) => {
            return (
              <Marker
                key={item.id}
                draggable
                flat
                position={getPositionFromPoint(item.coordinate ?? '')}>
                <View style={{ alignItems: 'center' }}>
                  <SvgXml
                    {...{
                      width: 36 * hp, height: 36 * hp
                    }}
                    // xml={item.type === '0' ? Zhy : Xfy}
                    xml={Car}
                  />
                  <Text style={{
                    color: '#000',
                    fontSize: 12 * hp
                  }}>{item.name}</Text>
                </View>
              </Marker>
            );
          })}
          {/* 灾情Circle渲染 */}
          {PoliceMapState.disasterPointList.map(item => {
            return (
              <DisasterItems
                key={item.id}
                renderList={item.disasters}
                center={getPositionFromPoint(
                  item.coordinate ?? '',
                )}></DisasterItems>
            );
          })}
        </MapView>
        <BaseSidebar
          contentStyles={{
            height: 600 * hp,
            padding: 20
          }}>
          <Text style={styles.title}>人员力量</Text>
          <View style={{
            flexDirection: 'row'
          }}>
            <View style={{ alignItems: 'center', marginRight: 20 }}>
              <DraxView
                longPressDelay={200}
                onDragStart={() => {
                  setTitle('指挥长')
                }}
                onDragEnd={data => {
                  currentPosition.current = data.dragAbsolutePosition
                  setVisible(true)
                }}>

                <SvgXml
                  {...styles.icon}
                  xml={Zhy}
                />
              </DraxView>
              <Text>指挥长</Text>
            </View>
            <View style={{ alignItems: 'center' }}>
              <DraxView
                longPressDelay={200}
                style={{
                  flexDirection: 'column',
                  alignItems: 'center'
                }}
                onDragStart={() => {
                  setTitle('指挥员')
                }}
                onDragEnd={data => {
                  currentPosition.current = data.dragAbsolutePosition
                  setVisible(true)

                }}>

                <SvgXml
                  {...styles.icon}
                  xml={Xfy}
                />
              </DraxView>
              <Text>指挥员</Text>
            </View>

          </View>
          <Text style={styles.title}>车辆力量</Text>
          <View style={{
            flexDirection: 'row'
          }}>
            <DraxView
              longPressDelay={200}
              onDragEnd={data => {
                currentPosition.current = data.dragAbsolutePosition
                MapViewRef.current?.getLatLng(currentPosition.current as Position).then((LatLng) => {
                  dispatch({
                    type: 'setCommandPostList',
                    value: [...PoliceMapState.commandPostList, {
                      name: selectValue.current.realName,
                      patrolCommandId: patrolCommandIdRef.current,
                      coordinate: Object.values(LatLng).join(','),
                      type: title === '指挥长' ? '0' : "1"
                    }],
                  });
                  setVisible(false)
                })
              }}>

              <SvgXml
                {...styles.icon}
                xml={Car}
              />
            </DraxView>
          </View>

        </BaseSidebar>
      </DraxProvider></>
  );
};
